package com.maserb.monitor.author;

import com.maserb.monitor.entity.UserEntity;
import com.maserb.monitor.enums.RoleEnum;
import com.maserb.monitor.service.author_manage.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.PasswordService;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class MonitorShiroRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    @Autowired
    private PasswordService passwordService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        UserEntity user = (UserEntity) principals.getPrimaryPrincipal();
        authorizationInfo.addRole(user.getRole().toString());
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户的输入的账号.
        String username = (String) token.getPrincipal();

        if ("admin".equals(username)) {
            UserEntity user = new UserEntity();
            user.setUserName("admin");
            user.setRealName("admin");
            user.setPassword("1");
            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                    user,
                    "1",
                    null,
                    getName()
            );

            return authenticationInfo;
        } else {
            UserEntity user = userService.findByUserName(username);
            if (user == null) {
                return null;
            }

            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                    user,
                    user.getPassword(),
                    null,
                    getName()
            );
            return authenticationInfo;
        }
    }
}
